<template>
  <div class="chat-container">
    <div class="chat-content" ref="chatContent">
      <div v-for="(item, index) in chatList" :key="index" :class="['chat-item', item.role === 'user' ? 'user-item' : 'ai-item']">
        <div class="chat-role">{{ item.role === 'user' ? '我' : 'AI' }}</div>
        <div class="chat-message">{{ item.content }}</div>
      </div>
    </div>

    <div class="input-area">
      <textarea v-model="userInput" placeholder="输入消息或点击语音按钮" class="text-input" @keyup.enter="sendMessage"></textarea>
      <button class="voice-btn" @click="toggleVoiceRecognition" :disabled="isRecognizing">
        {{ isRecognizing ? '正在录音...' : ' 语音' }}
      </button>
      <button class="send-btn" @click="sendMessage" :disabled="!userInput.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getRequest,postRequest } from './services/api.js';
const route = useRoute();
const router = useRouter();
const roleName = ref(route.query.roleName || '');
const userInput = ref(''); 
const chatList = ref([]);
const isRecognizing = ref(false);
let recognition = null; 
onMounted(async () => {
    if (!roleName.value) {
        alert('未选择聊天角色，请返回选择角色');
        router.push('/');
        return;
    }
    try {
        const res = await getRequest('/role/getRoleByName', { roleName: roleName.value });
        if (res.code === '200' && res.data) {
            chatList.value.push({
                role: 'AI',
                content: `你好，我是${roleName.value}，有什么可以帮你的吗？`
            }); 
        } else {
            alert('获取角色信息失败：' + (res.message || '未知错误'));
            router.push('/');
        }
    } catch (error) {
        console.error('获取角色信息出错：', error);
        alert('网络异常，无法获取角色信息');
        router.push('/');
    }
});
const initVoiceRecognition = () => {
  const rec = new webkitSpeechRecognition();
  rec.lang = 'zh-CN';
  rec.interimResults = false; 
  rec.maxAlternatives = 1;
  rec.onresult = (event) => {
    const transcript = event.results[0][0].transcript;
    userInput.value = transcript;
  };
  rec.onend = ()=>{
    isRecognizing.value = false;
    rec.stop();
  };
  rec.onerror = (err) => {
    console.error('语音识别错误：', err);
    alert('语音识别失败，请重试～');
    isRecognizing.value = false;
    rec.stop();
  };

  return rec;
};


const toggleVoiceRecognition = () => {
  if (!recognition) {
    recognition = initVoiceRecognition();
    if (!recognition) return;
  }
  if (isRecognizing.value) {
    recognition.stop();
    isRecognizing.value = false;
  } else {
    recognition.start();
    isRecognizing.value = true;
    userInput.value = ''; 
  }
};

const sendMessage = async () => {
  const content = userInput.value.trim();
  chatList.value.push({ role: 'user', content });
  userInput.value = '';
  scrollToBottom();
  try {
    const data = await postRequest('/ai/getAi', {
      userInput: content,
      roleName: roleName.value  
    });
    chatList.value.push({ role: 'AI', content: data.data.text });
    const aiVoiceBase64 = data.data.voiceBase64;
    if (aiVoiceBase64) {
      // 构造音频URL：data:audio/wav;base64,+Base64编码（百度TTS返回的是wav格式）
      const audioUrl = `data:audio/wav;base64,${aiVoiceBase64}`;
      // 创建Audio对象并播放
      const audio = new Audio(audioUrl);
      audio.play().catch(err => {
        console.error('语音播放失败：', err);
        alert('语音播放失败，请重试~');
      });
    }
  } catch (err) {
    console.error('调用AI接口失败：', err);
    chatList.value.push({ role: 'AI', content: '抱歉，服务器出错了，请重试～' });
  } finally {
    scrollToBottom(); 
  }
};

const scrollToBottom = async () => {
  await nextTick();
  const chatContent = document.querySelector('.chat-content');
  chatContent.scrollTop = chatContent.scrollHeight;
};
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.chat-container {
    display: flex;
    flex-direction: column;
    width: 100%; 
    height: 100vh; 
    background-color: #fff;
}

.chat-content { 
    padding: 1.5vw; 
    background-color: #f9fafb;
    overflow-y: auto;
    flex: 1;
}

.chat-item {
    margin-bottom: 1.5vh;
    width: 75vw;
    padding: 1.2vh 1.5vw;
    border-radius: 8px;
    word-wrap: break-word; 
}

.user-item {
    margin-left: auto;
    background-color: #3b82f6;
    color: white;
}

.ai-item {
    margin-right: auto;
    background-color: white;
    border: 1px solid #e5e7eb;
}

.chat-role {
    font-size: 12px;
    margin-bottom: 0.8vh;
    opacity: 0.8;
}

.chat-message{
  font-size: 15px;
}

.input-area {
    display: flex;
    align-items: center; 
    padding: 1vh 1vw;
    background-color: white;
}


.text-input {
    height: 7vh;
    padding: 1.2vh 1.5vw;
    font-size: 15px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    resize: none;
    outline: none;
    flex: 1; 
}

.voice-btn,.send-btn {
    width: 12vw;
    height: 7vh;
    border: none;
    margin-top: 1vh;
    border-radius: 1vw;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center; 
}

.voice-btn {
    background-color: #fbbf24;
    color: white;
}

.voice-btn:disabled {
    background-color: #fcd34d;
    cursor: not-allowed;
}

.send-btn {
    background-color: #3b82f6;
    color: white;
}

.send-btn:disabled {
    background-color: #93c5fd;
    cursor: not-allowed;
}
</style>